﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObviousCode.Aspect.PluginLibrary.Interfaces;
using ObviousCode.Aspect.PluginLibrary.Descriptors;
using ObviousCode.UI.Aspect.PluginLibrary.Interfaces;
using ObviousCode.Common.Utils.Library.Exceptions;
using ObviousCode.Common.Utils.Library;

namespace ObviousCode.Aspect.PluginLibrary.Abstract
{
    public abstract class BaseSurfaceRelationshipFactory<T> : ISurfaceRelationshipFactory<T> where T : ISurfaceRelationship
    {
        SurfaceRelationshipDescriptorStore _store;

        public BaseSurfaceRelationshipFactory(IAspectDesigner host)
        {
            Host = host;
            _store = new SurfaceRelationshipDescriptorStore();
        }

        public void Setup() {  }
        public void TearDown() { }

        public ISurfaceRelationship BuildRelationship(IAspectItem source, IAspectItem destination, string key)
        {
            if (!_store.ContainsKey(key)) ExceptionBuilder.Format("Key \"{0}\" not located in {1}.", key, GetType().ToString());

            IAspectRelationship tag = _store[key].Builder(new Pair<IAspectItem, IAspectItem>(source, destination), new object[] { } );

            ISurfaceRelationship relationship = BuildNewRelationship();

            relationship.Tag = tag;

            relationship.Theme = _store[key].Theme;                       

            return relationship;
        }

        protected abstract T BuildNewRelationship();

        public void RegisterRelationshipBuilderCallback(string key, Func<Pair<IAspectItem, IAspectItem>, object[], IAspectRelationship> callback)
        {
            _store[key].Builder = callback;
        }

        public void RegisterSurfaceRelationshipDescriptor(string key, SurfaceRelationshipDescriptor surfaceRelationshipDescriptor)
        {
            _store[key] = surfaceRelationshipDescriptor;            
        }

        protected IAspectDesigner Host { get; private set; }        
    }
}
